package com.study.dao.impl;

import com.study.dao.LendDao;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate5.HibernateCallback;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;

import java.util.List;

public class LendDaoImpl extends HibernateDaoSupport implements LendDao {
    @Override
    public void addLend(Lend lend, Book book, Student student) {
        //添加图书信息
        this.getHibernateTemplate().save(lend);
        //修改图书信息，库存量-1
        this.getHibernateTemplate().update(book);
        //修改学生信息，借书量+1
        this.getHibernateTemplate().update(student);
    }

    @Override
    public List selectBook(final String readerId, final int pageNow, final int pageSize) {
        List list = (List) getHibernateTemplate().execute(
                new HibernateCallback() {
                    int size = pageNow * pageSize - pageSize;

                    @Override
                    public Object doInHibernate(Session session) throws HibernateException {
                        Query query = session.createSQLQuery("select l.bookId,l.ISBN,b.bookName,b.publisher, b.price,l.ltime from Lend as l,Book as b where l.readerId=? and b.isbn=l.ISBN");
                        query.setParameter(0, readerId);
                        query.setFirstResult(size);
                        query.setMaxResults(pageSize);
                        List l = query.list();
                        return l;
                    }
                });                                    //内部类，返回一个List
        return list;
    }

    @Override
    public int selectBookSize(String readerId) {
        return this.getHibernateTemplate().find("from Lend where readerId=?", readerId).size();
    }

    @Override
    public Lend selectByBookId(String bookId) {
        return (Lend) getHibernateTemplate().get(Lend.class, bookId);
    }

    @Override
    public Lend selectByBookISBN(String ISBN) {
        Lend lend = null;
        List list = this.getHibernateTemplate().find("from Lend where isbn=?", ISBN);
        if (list.size() > 0) {
            lend = (Lend) list.get(0);
        }
        return lend;
    }
}

